import os
import pandas as pd
import json
import chardet

UPLOAD_FOLDER = "uploads"


def read_csv_with_encoding(fpath):
    """尝试读取CSV文件，自动检测编码"""
    with open(fpath, 'rb') as f:
        raw = f.read()
        result = chardet.detect(raw)
        encoding = result['encoding'] or 'utf-8'
    try:
        return pd.read_csv(fpath, encoding=encoding)
    except Exception as e:
        raise ValueError(f"{fpath} 读取失败（编码={encoding}）：{str(e)}")


def save_uploaded_file(file):
    """保存上传的文件（支持多层路径）"""
    filepath = os.path.join(UPLOAD_FOLDER, file.filename)
    dirpath = os.path.dirname(filepath)
    if not os.path.exists(dirpath):
        os.makedirs(dirpath)
    file.save(filepath)



def list_uploaded_files():
    """列出上传目录下的所有 CSV 和 JSON 文件"""
    if not os.path.exists(UPLOAD_FOLDER):
        return []
    return [f for f in os.listdir(UPLOAD_FOLDER) if f.endswith('.csv') or f.endswith('.json')]


def load_selected_files(file_names):
    """读取用户选择的一个或多个文件，返回 DataFrame 列表"""
    all_data = []
    for fname in file_names:
        fpath = os.path.join(UPLOAD_FOLDER, fname)
        try:
            if fname.endswith('.csv'):
                df = read_csv_with_encoding(fpath)
            elif fname.endswith('.json'):
                df = pd.read_json(fpath)
            else:
                continue  # 非支持文件类型，跳过
            all_data.append(df)
        except Exception as e:
            print(f"[错误] 读取文件 {fname} 时出错: {e}")
            # 可选：继续下一个文件 or raise 异常
    return all_data


def preview_file(fname, n=5):
    """预览文件内容的前 n 行"""
    fpath = os.path.join(UPLOAD_FOLDER, fname)
    try:
        if fname.endswith('.csv'):
            df = read_csv_with_encoding(fpath)
        elif fname.endswith('.json'):
            df = pd.read_json(fpath)
        else:
            return None
        return df.head(n).to_dict(orient="records")
    except Exception as e:
        print(f"[错误] 预览文件 {fname} 时出错: {e}")
        return None